package com.xiaoshuidi.cloud.module.contract.controller.app.contract;

import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageParam;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.contract.controller.admin.contract.vo.ElectronicContractGenerateRespVO;
import com.xiaoshuidi.cloud.module.contract.controller.admin.contract.vo.RoomContractRespVO;
import com.xiaoshuidi.cloud.module.contract.controller.app.contract.vo.RenterCheckRespVO;
import com.xiaoshuidi.cloud.module.contract.convert.contract.ContractConvert;
import com.xiaoshuidi.cloud.module.contract.dal.dataobject.contract.ContractRoomDO;
import com.xiaoshuidi.cloud.module.contract.dal.dataobject.roommeta.ContractRoommateDO;
import com.xiaoshuidi.cloud.module.contract.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.contract.service.contract.ContractRoomService;
import com.xiaoshuidi.cloud.module.contract.service.contract.ElectronicContractService;
import com.xiaoshuidi.cloud.module.contract.service.roommate.ContractRoommateService;
import com.xiaoshuidi.cloud.module.contract.vo.ContractRoomReqVO;
import com.xiaoshuidi.cloud.module.contract.vo.ContractRoomRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

import static com.xiaoshuidi.cloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.error;
import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.success;

@Tag(name = "APP - 合同模块")
@RestController
@RequestMapping(ApiConstants.NAME + "/app" )
@Validated
@Slf4j
public class AppContractController {

    @Resource
    private ElectronicContractService electronicContractService;

    @Resource
    private ContractRoomService contractRoomService;

    @Resource
    private ContractRoommateService contractRoommateService;

    @GetMapping("/sign")
    @Operation(summary = "合同签约")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
    @Parameter(name = "phone", description = "签约手机号", required = true, example = "12312341234")
    public CommonResult extsign(@RequestParam("contractId") Long contractId, @RequestParam("phone") String phone) {
        try {
            return success(electronicContractService.extsign(contractId,phone));
        }  catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }

    /**
     * 租客端合同查询
     * @param pageParam
     * @return
     */
    @GetMapping("/get-contract-list")
    @Operation(summary = "租客端合同查询")
    public CommonResult<PageResult<ContractRoomRespVO>> getCustomerContract(PageParam pageParam) {
        try {
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();

            if (pageParam.getPageNo()==null) {
                pageParam.setPageNo(1);
            }
            if (pageParam.getPageSize()==null) {
                pageParam.setPageSize(10);
            }
            log.info(JSONObject.toJSONString(pageParam));
            PageResult<ContractRoomRespVO> customerContract = contractRoomService.getCustomerContract(pageParam,loginUserId);
            return success(customerContract);
        }  catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }

    @GetMapping("/get-contract-detail")
    @Operation(summary = "租客端合同查询")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
    public CommonResult<RoomContractRespVO> getRoomContract(@RequestParam("id") Long id) {
        try {
            ContractRoomDO contractRoomDO = contractRoomService.get(id);
            RoomContractRespVO roomContract = ContractConvert.INSTANCE.convert1(contractRoomDO);
            return success(roomContract);
        } catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }

    /**
     * 根据登录人id获取房间
     * @return
     */
    @GetMapping("/get-roomIds")
    @Operation(summary = "根据登录人id获取房间")
    public CommonResult<List<ContractRoomReqVO>> getRoomIdByUserId() {
        try {
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
            List<ContractRoomReqVO> contractRoomReqVO = contractRoomService.getRoomIdByUserId(loginUserId);
            return success(contractRoomReqVO);
        }  catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }

    /**
     * 获取电子合同（合同预览、下载）
     */
    @GetMapping("/get-electronic-contract")
    @Operation(summary = "获取电子合同")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('contract:generate')")
    public CommonResult<ElectronicContractGenerateRespVO> generateElectronicContract(@RequestParam("contractId") Long contractId) {
        try {
            return success(electronicContractService.generateElectronicContract(contractId));
        }  catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }

    /**
     * 判断是否有安全协议需要签署
     */
    @GetMapping("/check-safe-protocol")
    @Operation(summary = "判断是否有安全协议需要签署")
    public CommonResult<Boolean> checkSafeProtocol() {
        try {
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
            if (Objects.isNull(loginUserId)) {
                throw exception(GlobalErrorCodeConstants.UNAUTHORIZED);
            }
            List<ContractRoommateDO> byParam = contractRoommateService.getRequireSignSafeRoommateList(loginUserId);
            if (CollectionUtils.isNotEmpty(byParam)){
                return success(true);
            }
            return success(false);
        }  catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }


    /**
     * 获取安全协议签署地址
     */
    @GetMapping("/get-sign-url")
    @Operation(summary = "获取安全协议签署地址")
    public CommonResult<String> getSignUrl() {
        try {
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
            if (Objects.isNull(loginUserId)) {
                throw exception(GlobalErrorCodeConstants.UNAUTHORIZED);
            }
            return success(electronicContractService.getSafeProtocolSignAddr(loginUserId));
        } catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }


    /**
     * 校验租客信息（待签约合同，待支付账单，待签署安全协议，待处理交房）
     */
    @GetMapping("/check-renter-info")
    @Operation(summary = "校验租客信息（待签约合同，待支付账单，待签署安全协议，待处理交房）")
    public CommonResult<RenterCheckRespVO> checkRenterInfo() {
        try {
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
            if (Objects.isNull(loginUserId)) {
                throw exception(GlobalErrorCodeConstants.UNAUTHORIZED);
            }
            return success(contractRoomService.checkRenterInfo(loginUserId));
        }  catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }

    /**
     * 业主合同签约
     */
    @GetMapping("/owner-sign")
    @Operation(summary = "业主合同签约")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
    @Parameter(name = "phone", description = "签约手机号", required = true, example = "12312341234")
    public CommonResult ownerExtsign(@RequestParam("contractId") Long contractId, @RequestParam("phone") String phone) {
        try {
            return success(electronicContractService.ownerExtsign(contractId,phone));
        }  catch (ServiceException e) {
            return error(e.getCode(),e.getMessage());
        }
    }

}
